package com.blank.shop.seata.order;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.blank.shop.seata.ShopAlibabaSeataApplication;
import com.blank.shop.seata.domain.Order;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <br/>Date 2021/8/30
 * <br/>Time 16:09:44
 *
 * @author _blank
 */
@Profile({ShopAlibabaSeataApplication.PROFILE_ORDER})
@RestController
public class OrderController {

    public static final String INSERT_SQL = "INSERT INTO `t_order` (`id`,`user_id`,`product_id`,`count`,`money`,`status`) VALUES (NULL,?, ?, ?, ?, ?)";
    public static final String UPDATE_SQL = "UPDATE `t_order` SET STATUS=? WHERE user_id=? AND status=0";

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建订单
     *
     * @param order 订单
     * @return org.springframework.http.ResponseEntity
     */
    @PostMapping(path = {"order-create"})
    public ResponseEntity<String> create(@RequestBody Order order) {
        try {
            DynamicDataSourceContextHolder.push(ShopAlibabaSeataApplication.DS_ORDER);
            final int affectedRows = this.jdbcTemplate.update(INSERT_SQL
                    , order.getUserId()
                    , order.getProductId()
                    , order.getCount()
                    , order.getMoney()
                    , order.getStatus()
            );
            return ResponseEntity.ok("order-create-ok-" + affectedRows);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

    /**
     * 更新订单状态
     *
     * @param order 订单
     * @return org.springframework.http.ResponseEntity
     */
    @PostMapping(path = {"order-update"})
    public ResponseEntity<String> update(@RequestBody Order order) {
        try {
            DynamicDataSourceContextHolder.push(ShopAlibabaSeataApplication.DS_ORDER);
            final int affectedRows = this.jdbcTemplate.update(UPDATE_SQL
                    , order.getStatus()
                    , order.getUserId()
            );
            return ResponseEntity.ok("order-update-ok-" + affectedRows);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("failed");
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

}
